package model;

import java.util.List;

import Repository.Repository;
import Repository.RepositoryFactory;
import constants.SMSConstants;

public class MergeRuleSelector implements RuleSelector {

	private Repository ruleRepository = RepositoryFactory
			.getRepository(SMSConstants.RULE);
	private SMSObject smsObject;

	public MergeRuleSelector(SMSObject smsObject) {
		this.smsObject = smsObject;
	}

	public boolean processRuleRequest() {
		Rule mergeRule = getRule();
		return applyRule(mergeRule);

	}

	public Rule getRule() {

		if (smsObject instanceof Lead) {
			return (Rule) ruleRepository.retrieve(SMSConstants.LEAD,
					SMSConstants.MERGE);
		}
		return new NullRule();

	}

	public boolean applyRule(Rule rule) {

		if (smsObject instanceof Lead) {
			if (rule.getRuleDescripton().equalsIgnoreCase("same name")) {
				Repository repository = RepositoryFactory.getRepository(SMSConstants.LEAD);
				List assignedLeads = repository.retrieve("Assigned");
				Lead assignedLead = (Lead) smsObject;
				for (Object o : assignedLeads) {
					Lead l = (Lead) o;
					if (l.getManagedByUser().getId() == smsObject.getManagedByUser().getId()
							&& l.getName().equalsIgnoreCase(assignedLead.getName())) {
						
						repository.delete(l.getSmsObjId());
					}
				}
			}
		}

		return true;
	}

}
